package me.sunpeng.buffer;

import org.junit.Test;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;

/**
 * @author sp
 */
public class BufferDemo1 {
    final static String PATH = "iofile\\1.txt";
    final static String MODE = "rw";

    @Test
    public void buffer01() throws IOException {
        //打开一个channel
        RandomAccessFile accessFile = new RandomAccessFile(PATH, MODE);
        FileChannel channel = accessFile.getChannel();

        //创建Buffer,大小
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        //读
        int byteRead = channel.read(buffer);

        while (byteRead != -1) {
            //read模式
            buffer.flip();
            while (buffer.hasRemaining()) {
                System.out.println(((char) buffer.get()));
            }
            buffer.clear();
            byteRead = channel.read(buffer);

        }
        accessFile.close();

    }

    @Test
    public void buffer02() {

        // 分配新的 int 缓冲区，参数为缓冲区容量
        // 新缓冲区的当前位置将为零，其界限(限制位置)将为其容量。
        // 它将具有一个底层实现数组，其数组偏移量将为零
        IntBuffer buffer = IntBuffer.allocate(8);

        //buffer
        for (int i = 0; i < buffer.capacity(); i++) {
            int j = 2 * (i + 1);
            buffer.put(j);
        }
        // 重设此缓冲区，将限制设置为当前位置，然后将当前位置设置为0
        buffer.flip();
        // 查看在当前位置和限制位置之间是否有元素
        while (buffer.hasRemaining()) {
        // 读取此缓冲区当前位置的整数，然后当前位置递增
            int j = buffer.get();
            System.out.print(j + " ");
        }

    }

}
